package com.xp.tinyurl.admin.controller;

import com.xp.tinyurl.admin.dto.ChannelQueryDTO;
import com.xp.tinyurl.admin.vo.EnumTypeVO;
import com.xp.tinyurl.common.base.PageList;
import com.xp.tinyurl.common.base.ResultVO;
import com.xp.tinyurl.common.base.ResultVOBuilder;
import com.xp.tinyurl.model.Channel;
import com.xp.tinyurl.service.ChannelService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description 通道管理
 * @Author chengguo.pei
 * @Date 2021/9/22 18:08
 */
@Slf4j
@RequestMapping("/admin/channel")
@RestController
public class ChannelController {

    @Autowired
    private ChannelService channelService;

    /**
     * 获取短链接通道
     * @param channelQueryDTO
     * @return
     */
    @RequestMapping(value = "/getShorterUrlChannels")
    public ResultVO getShorterUrlChannels(@Valid ChannelQueryDTO channelQueryDTO) {

        Map<String, Object> param = new HashMap<>(2);
        param.put("pageSize", channelQueryDTO.getPageSize());
        param.put("startPage", channelQueryDTO.getPageNo());

        List<Channel> list = channelService.getPageList(param);
        Integer count = channelService.getPageListCount(param);
        PageList<Channel> pageList = PageList.build(list, count);
        pageList.setPageNum(channelQueryDTO.getPageNo());
        pageList.setPageSize(channelQueryDTO.getPageSize());
        return ResultVOBuilder.success(pageList);
    }

    /**
     * 获取短链接通道域名枚举
     * @return
     */
    @RequestMapping(value = "/getShorterUrlChannelEnum")
    public ResultVO getShorterUrlChannelEnum() {
        ChannelQueryDTO channelQueryDTO = new ChannelQueryDTO();
        channelQueryDTO.setPageNo(1);
        channelQueryDTO.setPageSize(100);
        Map<String, Object> param = new HashMap<>(2);
        param.put("pageSize", channelQueryDTO.getPageSize());
        param.put("startPage", channelQueryDTO.getPageNo());
        List<Channel> list = channelService.getPageList(param);
        //build data
        List<EnumTypeVO> enumTypeVoList = new ArrayList<>();
        if(CollectionUtils.isEmpty(list)){
            return ResultVOBuilder.success(enumTypeVoList);
        }
        list.stream().forEach(channel -> {
            EnumTypeVO enumTypeVO = new EnumTypeVO();
            enumTypeVO.setId(channel.getId().toString());
            enumTypeVO.setName(channel.getMainDomainName() + "-" + channel.getMainDomainProvider());
            enumTypeVoList.add(enumTypeVO);
        });
        return ResultVOBuilder.success(enumTypeVoList);
    }
}
